import React from 'react';
import ReactDOM from 'react-dom/client';

import { HashRouter } from 'react-router-dom'

import App from './App';
//session加载失败
import SessionFail from './component/sessionFall'
//加载组件
import PageLoading from './component/pageLoading'

//api
import { getSession } from './utils/axiosRequest/api'
//缓存
import { setCache, removeAllCache } from './utils/cache/'
import { session_cache_key } from './utils/cache/cacheKey'
//加解密
import { encryptMD5 } from "./utils/crypt/index"

// 初始化函数
const initializeApp = async () => {
  //现展示加载状态
  const loadRoot = createRootView();
  loadRoot.render(<PageLoading ></PageLoading>);
  //session请求参数
  const timestamp = Date.now().toString();
  const issue = "hm";
  const version = "V100";
  const channel = "web";
  const author = "PCS";
  const permission = "10117aaa";
  //签名按照顺序channel->version->author->permission->issue全小写再md5
  const signature = timestamp.toLowerCase() + channel.toLowerCase() + version.toLowerCase() + author.toLowerCase() + permission.toLowerCase() + issue.toLowerCase()
  //构建请求参数
  const params = new Map()
  params.set('timestamp', timestamp)
  params.set('issue', issue)
  params.set('version', version)
  params.set('channel', channel)
  params.set('author', author)
  params.set('permission', permission)
  params.set('signature', encryptMD5(signature))
  try {
    const response = await getSession(params);
    //先删除所有缓存
    removeAllCache()
    //保存session
    const data = response.data
    setCache(session_cache_key, data.data.sessionId);
    loadRoot.unmount()//先卸载加载状态
    const normalRoot = createRootView();
    normalRoot.render(
      <HashRouter>
        <App />
      </HashRouter>
    );
  } catch (error) {
    loadRoot.unmount()//先卸载加载状态
    const failRoot = createRootView();
    failRoot.render(<SessionFail ></SessionFail>);
  }
};

const createRootView = () => {
  return ReactDOM.createRoot(document.getElementById('root'))
}


initializeApp();